package com.zgx.plus.system.controller;

import cn.hutool.core.map.MapUtil;
import com.zgx.plus.common.aop.Log;
import com.zgx.plus.common.constant.ComConstant;
import com.zgx.plus.common.response.R;
import com.zgx.plus.security.model.LoginBody;
import com.zgx.plus.security.service.SysPermissionService;
import com.zgx.plus.security.service.TokenService;
import com.zgx.plus.system.api.vos.SysUserVo;
import com.zgx.plus.system.biz.SysLoginService;
import com.zgx.plus.system.api.pos.SysUser;
import com.zgx.plus.system.service.SysMenuService;
import com.zgx.plus.system.api.vos.RouterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 */
@RestController
public class SysLoginController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private SysMenuService menuService;
    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public R<HashMap<String, String>> login(@RequestBody LoginBody loginBody) {
        return R.ok(MapUtil.of(ComConstant.KEY_TOKEN, loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid())));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @Log
    @GetMapping("getInfo")
    public R<Map<String, Object>> getInfo() {
        SysUserVo user = tokenService.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Map<String,Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("permissions", permissions);
        return R.ok(map);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public R<List<RouterVo>> getRouters() {
        return R.ok(menuService.buildMenus(menuService.selectMenuTreeByUserId(tokenService.getLoginUser().getUserId())));
    }
}
